<template>
    <div class="app-container">
        <vxe-grid ref="xGrid" v-if="tableLoad" v-bind="gridOptions" @checkbox-change="handleSelectionChange">
            <template #toolbar_buttons>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['monitor:job:remove']">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" @click="handleClean" v-hasPermi="['monitor:job:remove']">清空</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
                    </el-col>
                </el-row>
            </template>
            <template #slotJobGroup="{ row }">
                <dict-tag :options="sys_job_group" :value="row.jobGroup" />
            </template>
            <template #slotStatus="{ row }">
                <dict-tag :options="sys_common_status" :value="row.status" />
            </template>
            <template #action="{ row }">
                <el-button link type="primary" icon="View" @click="handleView(row)" v-hasPermi="['monitor:job:query']">详细</el-button>
            </template>
        </vxe-grid>

        <!-- 调度日志详细 -->
        <el-dialog title="调度日志详细" v-model="open" width="700px" append-to-body>
            <el-form :model="form" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="日志序号：">{{ form.jobLogId }}</el-form-item>
                        <el-form-item label="任务名称：">{{ form.jobName }}</el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="任务分组：">{{ form.jobGroup }}</el-form-item>
                        <el-form-item label="执行时间：">{{ form.createTime }}</el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="调用方法：">{{ form.invokeTarget }}</el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="日志信息：">{{ form.jobMessage }}</el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="执行状态：">
                            <div v-if="form.status == 0">正常</div>
                            <div v-else-if="form.status == 1">失败</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="异常信息：" v-if="form.status == 1">{{ form.exceptionInfo }}</el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="open = false">关 闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="JobLog" lang="ts">
    import { ref, getCurrentInstance, reactive, toRefs } from "vue";
    import { useRoute } from "vue-router";
    import { getJob } from "@/api/monitor/job";
    import { pageJobLog, delJobLog, cleanJobLog } from "@/api/monitor/jobLog";
    import { VxeGridInstance, VxeGridProps, VxeGridListeners } from "../../../../types/index";
    import XEUtils from "xe-utils";
    import { VXETable } from "../../../../packages/all";
    import { removeObjectNull } from "@/utils";
    const { proxy } = getCurrentInstance() as any;
    const { sys_common_status, sys_job_group } = proxy.useDict("sys_common_status", "sys_job_group");

    const open = ref(false);
    const ids = ref([]);
    const multiple = ref(true);
    const route = useRoute();
    const tableLoad = ref(false);
    const data: any = reactive({
        form: {},
    });

    const { form } = toRefs(data);
    const xGrid = ref({} as VxeGridInstance);

    const gridOptions = reactive<VxeGridProps>({
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: "13",
        height: "auto",
        rowId: "jobLogId",
        sortConfig: {
            trigger: "cell",
            remote: true,
        },
        filterConfig: {
            remote: true,
        },
        pagerConfig: {
            pageSize: 10,
            pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
            perfect: true,
        },
        formConfig: {
            titleWidth: 80,
            titleAlign: "right",
            items: [
                {
                    field: "status",
                    title: "执行状态",
                    span: 4,
                    itemRender: {
                        name: "$select",
                        options: sys_common_status,
                    },
                },
                {
                    field: "createTime",
                    title: "创建时间",
                    span: 5,
                    itemRender: {
                        name: "ElDatePicker",
                        props: {
                            valueFormat: "YYYY-MM-DD",
                            type: "daterange",
                            rangeSeparator: "-",
                            startPlaceholder: "开始日期",
                            endPlaceholder: "结束日期",
                        },
                    },
                },
                {
                    itemRender: {
                        name: "$buttons",
                        children: [
                            {
                                props: {
                                    type: "submit",
                                    content: "查询",
                                    status: "primary",
                                },
                            },
                            {
                                props: {
                                    type: "reset",
                                    content: "重置",
                                },
                            },
                        ],
                    },
                },
            ],
        },
        toolbarConfig: {
            refresh: true,
            zoom: true,
            export: proxy.$auth.hasPermi("monitor:job:export"),
            custom: true,
            slots: {
                buttons: "toolbar_buttons",
            },
        },
        proxyConfig: {
            paramsChangeLoad: false, //额外的请求参数改变时是否重新请求数据
            seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
            sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
            filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
            form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
            // 对应响应结果 { result: [], page: { total: 100 } }
            props: {
                result: "rows", // 配置响应结果列表字段
                total: "total", // 配置响应结果总页数字段
            },
            ajax: {
                // 接收 Promise
                query: ({ page, sorts, filters, form, params }: any) => {
                    // 处理时间范围查询
                    const createTime = proxy.addDateRange({}, form.createTime, "createTime");
                    const queryParams: any = Object.assign({}, form, page, params);
                    // 处理排序条件
                    const orderByColumn = <Array<String>>[];
                    const isAsc = <Array<Boolean>>[];
                    sorts.forEach((m: any) => {
                        orderByColumn.push(m.field);
                        isAsc.push(m.order);
                    });
                    queryParams.orderByColumn = orderByColumn.join(",");
                    queryParams.isAsc = isAsc.join(",");
                    // 处理筛选条件
                    filters.forEach(({ property, values }: any) => {
                        queryParams[property] = values.join(",");
                    });
                    return pageJobLog({
                        ...removeObjectNull(queryParams),
                    }).then((response) => {
                        return response;
                    });
                },
            },
        },
        columns: [
            { type: "checkbox", width: 60 },
            {
                field: "jobLogId",
                title: "日志编号",
                sortable: true,
            },
            {
                field: "jobName",
                title: "任务名称",
                sortable: true,
            },
            {
                field: "jobGroup",
                title: "任务组名",
                sortable: true,
                slots: {
                    default: "slotJobGroup",
                },
            },
            {
                field: "invokeTarget",
                title: "调用目标字符串",
                sortable: true,
            },
            {
                field: "jobMessage",
                title: "日志信息",
                sortable: true,
            },
            {
                field: "status",
                title: "执行状态",
                slots: {
                    default: "slotStatus",
                },
            },
            {
                field: "createTime",
                title: "执行时间",
                sortable: true,
                formatter({ cellValue }: any) {
                    return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                },
            },
            {
                title: "操作",
                width: 100,
                align: "center",
                fixed: "right",
                slots: { default: "action" },
            },
        ],
    });

    function addForm() {
        gridOptions.formConfig.items.unshift(
            {
                field: "jobName",
                title: "任务名称",
                span: 4,
                itemRender: {
                    name: "$input",
                    props: { placeholder: "请输入任务名称" },
                },
            },
            {
                field: "jobGroup",
                title: "任务组名",
                span: 4,
                itemRender: {
                    name: "$select",
                    options: sys_job_group,
                },
            }
        );
    }
    (() => {
        const jobId = route.params && route.params.jobId;
        if (jobId !== undefined && jobId != "0") {
            getJob(jobId).then((response) => {
                if (response["code"] == 200) {
                    gridOptions.formConfig.items.unshift(
                        {
                            field: "jobName",
                            title: "任务名称",
                            span: 4,
                            itemRender: {
                                name: "$input",
                                props: { placeholder: "请输入任务名称" },
                                defaultValue: response.data.jobName,
                            },
                        },
                        {
                            field: "jobGroup",
                            title: "任务组名",
                            span: 4,
                            itemRender: {
                                name: "$select",
                                options: sys_job_group,
                                defaultValue: response.data.jobGroup,
                            },
                        }
                    );
                } else {
                    addForm();
                }
                tableLoad.value = true;
            });
        } else {
            addForm();
            tableLoad.value = true;
        }
    })();

    // 返回按钮
    function handleClose() {
        const obj = { path: "/monitor/job" };
        proxy.$tab.closeOpenPage(obj);
    }

    // 多选框选中数据
    function handleSelectionChange(selection: any) {
        ids.value = selection.records.map((item: any) => item.jobLogId);
        multiple.value = !selection.records.length;
    }
    /** 详细按钮操作 */
    function handleView(row: any) {
        open.value = true;
        form.value = row;
    }
    /** 删除按钮操作 */
    function handleDelete(row: any) {
        proxy.$modal
            .confirm('是否确认删除调度日志编号为"' + ids.value + '"的数据项?')
            .then(function () {
                return delJobLog(ids.value);
            })
            .then(() => {
                // getList();
                xGrid.value.commitProxy("reload");
                proxy.$modal.msgSuccess("删除成功");
            })
            .catch(() => {});
    }
    /** 清空按钮操作 */
    function handleClean() {
        proxy.$modal
            .confirm("是否确认清空所有调度日志数据项?")
            .then(function () {
                return cleanJobLog();
            })
            .then(() => {
                // getList();
                xGrid.value.commitProxy("reload");
                proxy.$modal.msgSuccess("清空成功");
            })
            .catch(() => {});
    }
</script>
